package com.example.demo.controller;

import com.example.demo.common.AjaxResult;
import com.example.demo.common.AppVariable;
import com.example.demo.common.UserSessionUtils;
import com.example.demo.entity.*;
import com.example.demo.service.ArticleService;
import com.example.demo.thread.MyThread;
import com.example.demo.util.RemoveMarkdownTag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;

import static java.time.LocalDateTime.now;

@RestController
@RequestMapping("/art")
public class ArticleController {


    @Autowired
    private ArticleService articleService;




    /*
    * 查询文章列表
    * */
    @RequestMapping("/mylist")
    public AjaxResult getMyList(HttpServletRequest request){
        Userinfo userinfo = UserSessionUtils.getSessionUser(request);
        if (userinfo==null){
            return AjaxResult.fail(-1,"非法请求");
        }
        List<Articleinfo> list = articleService.getMyList(userinfo.getId());

        //在这里去除markdown的标签
        RemoveMarkdownTag removeMarkdownTag = new RemoveMarkdownTag();
        for(Articleinfo articleinfo:list){
            //在这里去除markdown的标签
            String text = articleinfo.getContent();
            articleinfo.setContent(removeMarkdownTag.removeMarkdownTags(text));
            //判断字符的数量，超过200字省略后边的东西
            if (articleinfo.getContent().length()>=200){
                String tmp = articleinfo.getContent().substring(0,200)+". . .";
                articleinfo.setContent(tmp);
            }
        }

        return AjaxResult.success(list);
    }


    /*
    * 删除文章
    * */
    @RequestMapping("/del")
    public AjaxResult del(HttpServletRequest request,Integer id){

        System.out.println("要删除的id:"+id);

        if (id == null || id <= 0){
            //参数有误
            return AjaxResult.fail(-1,"参数异常");
        }

        Userinfo user = UserSessionUtils.getSessionUser(request);
        if (user == null){
            return AjaxResult.fail(-2,"用户未登录");
        }


        System.out.println("对应的作者id:"+user.getId());

        return AjaxResult.success(articleService.del(id, user.getId()));
    }


    /**
     * 注销(退出登录)
     * */
    @RequestMapping("/logout")
    public AjaxResult logout(HttpSession session){
        session.removeAttribute(AppVariable.USER_SESSION_KEY);
        return AjaxResult.success(1);
    }


    @RequestMapping("/detail")
    public AjaxResult getDetail(Integer id){
        if (id==null || id<=0){
            return AjaxResult.fail(-1,"非法参数");
        }
        return AjaxResult.success(articleService.getDetail(id));
    }

    @RequestMapping("/incr-rcount")
    public AjaxResult incrRCount(Integer id){

        if (id!=null && id>0){
            return AjaxResult.success(articleService.incrRCount(id));
        }
        return AjaxResult.success(-1,"未知错误");
    }


    @RequestMapping("/add")
    public AjaxResult add(HttpServletRequest request,Articleinfo articleinfo){
        //1.非空校验
        if (articleinfo==null || !StringUtils.hasLength(articleinfo.getTitle())
                                || !StringUtils.hasLength(articleinfo.getContent())){
            return AjaxResult.fail(-1,"非法参数");
        }
        //2.数据库添加操作
        //a.得到当前登录的uid
        Userinfo userinfo = UserSessionUtils.getSessionUser(request);
        if ((userinfo==null || userinfo.getId()<=0)){
            //无效的登录用户
            return AjaxResult.fail(-2,"无效的登录用户");
        }
        articleinfo.setUid(userinfo.getId());
        //设置当前时间
        articleinfo.setCreatetime(now());
        articleinfo.setUpdatetime(now());
        //用户发布文章时，state先置为2，表示待审核状态
        articleinfo.setState(2);

        return AjaxResult.success(articleService.add(articleinfo));
    }



    @RequestMapping("/update")
    public AjaxResult update(HttpServletRequest request, Articleinfo articleinfo){
        //非空校验
        if (articleinfo== null || !StringUtils.hasLength(articleinfo.getContent())
                || !StringUtils.hasLength(articleinfo.getTitle())
                || articleinfo.getId()==null){
            //非法参数
            return AjaxResult.fail(-1,"非法参数");
        }
        //得到当前登录用户的id
        Userinfo userinfo = UserSessionUtils.getSessionUser(request);
        if (userinfo==null && userinfo.getId()==null){
            return AjaxResult.fail(-2,"无效用户");
        }
        //核心代码，设置当前文章uid，解决了修改文章归属人判定的问题
        articleinfo.setUid(userinfo.getId());
        articleinfo.setUpdatetime(LocalDateTime.now());
        //修改文章也是需要审核的
        articleinfo.setState(2);
        return AjaxResult.success(articleService.update(articleinfo));
    }



    /**
     * 查询列表根据分页
     * pindex 当前页码
     * psize  每页条数
     *
     * */

    @RequestMapping("/listbypage")
    public AjaxResult getListByPage(Integer pindex,Integer psize){
        //1.参数校正
        if (pindex==null || pindex<=1){
            pindex = 1;
        }
        if (psize==null || psize<1){
            psize = 2;
        }
        //分页公式的值 = （当前页码-1） * 每页显示条数
        int offsize = (pindex-1)*psize;
        //文章列表数据
        List<Articleinfo> list = articleService.getListByPage(psize,offsize);

        //在这里去除markdown的标签
        RemoveMarkdownTag removeMarkdownTag = new RemoveMarkdownTag();
        for(Articleinfo articleinfo:list){
            //在这里去除markdown的标签
            String text = articleinfo.getContent();
            articleinfo.setContent(removeMarkdownTag.removeMarkdownTags(text));
            //判断字符的数量，超过200字省略后边的东西
            if (articleinfo.getContent().length()>=200){
                String tmp = articleinfo.getContent().substring(0,200)+". . .";
                articleinfo.setContent(tmp);
            }
        }


        //当前列表总共有多少页
        //a.总共有多少条数据
        int totalCount = articleService.getCount();
        //b.总条数/每页显示条数
        double pcountdb = totalCount/(psize*1.0);
        //c.使用进一法得到总页数
        int pcount = (int)Math.ceil(pcountdb);
        HashMap<String,Object> result = new HashMap<>();
        result.put("list",list);
        result.put("pcount",pcount);
        return AjaxResult.success(result);

    }



    //存储草稿
    @RequestMapping("/adraft")
    public AjaxResult addDraft(Articleinfo articleinfo,HttpServletRequest request){
        //1.非空校验
        if (articleinfo==null || !StringUtils.hasLength(articleinfo.getTitle())
                || !StringUtils.hasLength(articleinfo.getContent())){
            return AjaxResult.fail(-1,"非法参数");
        }
        //2.数据库添加操作
        //a.得到当前登录的uid
        Userinfo userinfo = UserSessionUtils.getSessionUser(request);
        if ((userinfo==null || userinfo.getId()<=0)){
            //无效的登录用户
            return AjaxResult.fail(-2,"无效的登录用户");
        }
        articleinfo.setUid(userinfo.getId());
        //设置当前时间
        articleinfo.setCreatetime(now());
        articleinfo.setUpdatetime(now());

        return AjaxResult.success(articleService.addDraft(articleinfo));
    }

    //获取草稿
    @RequestMapping("/mydraft")
    public AjaxResult getMyDraft(HttpServletRequest request){
        Userinfo userinfo = UserSessionUtils.getSessionUser(request);
        if (userinfo==null){
            return AjaxResult.fail(-1,"非法请求");
        }
        List<Articleinfo> list = articleService.getMyDraft(userinfo.getId());

        //在这里去除markdown的标签
        RemoveMarkdownTag removeMarkdownTag = new RemoveMarkdownTag();
        for(Articleinfo articleinfo:list){
            //在这里去除markdown的标签
            String text = articleinfo.getContent();
            articleinfo.setContent(removeMarkdownTag.removeMarkdownTags(text));
            //判断字符的数量，超过200字省略后边的东西
            if (articleinfo.getContent().length()>=200){
                String tmp = articleinfo.getContent().substring(0,200)+". . .";
                articleinfo.setContent(tmp);
            }
        }

        return AjaxResult.success(list);
    }

    //删除草稿
    @RequestMapping("/deldraft")
    public AjaxResult delDraft(Integer id,HttpServletRequest request){
        if (id == null || id <= 0){
            //参数有误
            return AjaxResult.fail(-1,"参数异常");
        }

        Userinfo user = UserSessionUtils.getSessionUser(request);
        if (user == null){
            return AjaxResult.fail(-2,"用户未登录");
        }

        return AjaxResult.success(articleService.delDraft(id, user.getId()));
    }

    //根据草稿id查询对应草稿
    @RequestMapping("/mydraftdetail")
    public AjaxResult getDraftById(Integer id){
        if (id==null || id<=0){
            return AjaxResult.fail(-1,"非法参数");
        }
        return AjaxResult.success(articleService.getDraftById(id));
    }

    //修改草稿
    @RequestMapping("/updatedraft")
    public AjaxResult updateDraft(HttpServletRequest request,Articleinfo articleinfo){
        //非空校验
        if (articleinfo== null || !StringUtils.hasLength(articleinfo.getContent())
                || !StringUtils.hasLength(articleinfo.getTitle())
                || articleinfo.getId()==null){
            //非法参数
            return AjaxResult.fail(-1,"非法参数");
        }
        //得到当前登录用户的id
        Userinfo userinfo = UserSessionUtils.getSessionUser(request);
        if (userinfo==null && userinfo.getId()==null){
            return AjaxResult.fail(-2,"无效用户");
        }
        //核心代码，设置当前文章uid，解决了修改文章归属人判定的问题
        articleinfo.setUid(userinfo.getId());
        articleinfo.setUpdatetime(LocalDateTime.now());
        return AjaxResult.success(articleService.updateDraft(articleinfo));

    }

    //更加草稿id将草稿插入文章表中
    @RequestMapping("/adddraftById")
    public AjaxResult adddraftById(HttpServletRequest request,Integer id){
        //先根据id，查询草稿内容
        Articleinfo draft = articleService.getDraftById(id);
        //再将查询到的草稿插入到文章表中
        return add(request,draft);

    }


    public AjaxResult add1(HttpServletRequest request, Articleinfo articleinfo, String time){
        //1.非空校验
        if (articleinfo==null || !StringUtils.hasLength(articleinfo.getTitle())
                || !StringUtils.hasLength(articleinfo.getContent())){
            return AjaxResult.fail(-1,"非法参数");
        }
        //2.数据库添加操作
        //a.得到当前登录的uid
        Userinfo userinfo = UserSessionUtils.getSessionUser(request);
        if ((userinfo==null || userinfo.getId()<=0)){
            //无效的登录用户
            return AjaxResult.fail(-2,"无效的登录用户");
        }
        articleinfo.setUid(userinfo.getId());
        //设置当前时间
        String pattern = "yyyy-MM-dd HH:mm:ss";
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
        LocalDateTime createTime = LocalDateTime.parse(time,formatter);
        articleinfo.setCreatetime(createTime);
        articleinfo.setUpdatetime(createTime);
        System.out.println("完成了add1");

        return AjaxResult.success(articleService.add(articleinfo));
    }
    //定时发布文章
    @RequestMapping("/adddraftByIdTime")
    public AjaxResult adddraftByIdTime(HttpServletRequest request ,Integer id ,String time){

        System.out.println("确认时传来的id:"+id);

        if(time == "") {
            String now = now().toString();
            time = now.substring(0,10)+" "+now.substring(11,19);
            System.out.println("转换后的时间: "+time);
        }
        Userinfo userinfo = UserSessionUtils.getSessionUser(request);
        int uid = userinfo.getId();
        MyThread thread = new MyThread(uid,id,time,articleService);
        Thread t = new Thread(thread);
        t.start();

        return AjaxResult.success(1);

    }


    //文章赞加1
    @RequestMapping("/addgoodcount")
    public AjaxResult addGoodCount(Integer id){

        if (id==null || id<=0){
            return AjaxResult.fail(-1,"非法参数");
        }
        return AjaxResult.success(articleService.updateGCount(id));

    }

    //文章赞踩+1
    @RequestMapping("/addbadcount")
    public AjaxResult addBadCount(Integer id){

        if (id==null || id<=0){
            return AjaxResult.fail(-1,"非法参数");
        }
        return AjaxResult.success(articleService.updateBCount(id));

    }


    //将被管理员删除的文章转存为草稿
    @RequestMapping("/addDelArticleToDraft")
    public AjaxResult addDelArticleToDraft(Integer id){
        if (id==null || id<=0){
            return AjaxResult.fail(-1,"非法参数");
        }
        //根据id在articleinfo表中找对应文章
        Articleinfo articleinfo = articleService.getArticleById(id);
        articleinfo.setUpdatetime(now());
        //将找到的文章存到草稿中
        return AjaxResult.success(articleService.addDraft(articleinfo));
    }

    //清空所有的通知
    @RequestMapping("/cleanAll")
    public AjaxResult cleanAll(HttpServletRequest request){
        //获取当前用户id
        Userinfo userinfo = UserSessionUtils.getSessionUser(request);
        if (userinfo==null){
            return AjaxResult.fail(-1,"非法请求");
        }
        int uid = userinfo.getId();


        //从delArticle表中查询state为1的数据
        List<DelArticleinfo> list1 = articleService.getAllDelArticleByUId(uid);
        //将这些数据插入到historynoti表中
        for(DelArticleinfo delArticleinfo:list1){
            HistoryNotiinfo historyNotiinfo = new HistoryNotiinfo();
            historyNotiinfo.setUid(delArticleinfo.getUid());
            historyNotiinfo.setContent("你的标题为\" "+ delArticleinfo.getTitle()  + " \"的文章已被管理员删除 ");
            historyNotiinfo.setTime(delArticleinfo.getDelTime());
            articleService.insertHistoryToHistoryNoti(historyNotiinfo);
        }
        //更新state为1的数据，改成2
        int a = articleService.updateDelArticleState(uid);

        //从checkarticle表中查询state为1 2的数据
        List<CheckArticleinfo> list2 = articleService.getAllCheckArticleInCheckArticle(uid);
        //将这些数据插入到historyboti表中
        for(CheckArticleinfo checkArticleinfo:list2){
            //将此通知存入historynoti表中
            String content = "";
            if (checkArticleinfo.getState()==1){
                content = "您的标题为\"" + checkArticleinfo.getTitle() + "\"的文章已经被审核通过";
            }else if(checkArticleinfo.getState()==2){
                content = "您的标题为\"" + checkArticleinfo.getTitle() + "\"的文章没有被审核通过";
            }
            HistoryNotiinfo historyNotiinfo = new HistoryNotiinfo();
            historyNotiinfo.setUid(uid);
            //根据aid在checkarticle中获取时间
            historyNotiinfo.setTime(checkArticleinfo.getDelTime());
            historyNotiinfo.setContent(content);
            articleService.insertHistoryToHistoryNoti(historyNotiinfo);
        }
        //将historynoti表中state为1 2的数据统一 加2
        int b = articleService.updateAllCheckArticleStateAddTwo(uid);


        if (a>0||b>0){
            return AjaxResult.success(1);
        }else{
            return AjaxResult.fail(-1);
        }

    }




    //删除单条管理员删除文章的通知
    @RequestMapping("/deleteNoti")
    public AjaxResult deleteNoti(Integer aid,String superTable,Integer state,String title,HttpServletRequest request){
        if (aid==null || aid<=0){
            return AjaxResult.fail(-1,"非法参数");
        }
        Userinfo user = UserSessionUtils.getSessionUser(request);
        if (user == null){
            return AjaxResult.fail(-2,"用户未登录");
        }
        int uid = user.getId();

        int a  = 0,b=0;
        if (superTable.equals("delArticle")){
            //删除delArticle表中的通知
            a = articleService.deleteDelNotiByAid(aid);
            //将此通知存入historynoti表中
            String content = "你的标题为\" "+ title  + " \"的文章已被管理员删除 ";
            HistoryNotiinfo historyNotiinfo = new HistoryNotiinfo();
            historyNotiinfo.setUid(uid);
            //根据aid获取此条记录的时间
            LocalDateTime deltime = articleService.getDelTimeArticleByAid(aid);
            historyNotiinfo.setTime(deltime);
            historyNotiinfo.setContent(content);
            articleService.insertHistoryToHistoryNoti(historyNotiinfo);
        }
        if (superTable.equals("checkArticle")){
            b = articleService.updateCheckeNotiByAid(aid,state+2);
            //将此通知存入historynoti表中
            String content = "";
            if (state==1){
                 content = "您的标题为\"" + title + "\"的文章已经被审核通过";
            }else if(state==2){
                content = "您的标题为\"" + title + "\"的文章没有被审核通过";
            }
            HistoryNotiinfo historyNotiinfo = new HistoryNotiinfo();
            historyNotiinfo.setUid(uid);
            //根据aid在checkarticle中获取时间
            LocalDateTime delTime = articleService.getDelTimeInCheckArticleByAid(aid);
            historyNotiinfo.setTime(delTime);
            historyNotiinfo.setContent(content);
            articleService.insertHistoryToHistoryNoti(historyNotiinfo);
        }
        if (a >0 || b>0){
            return AjaxResult.success(1);
        }else {
            return AjaxResult.fail(-1);
        }


    }



}
